package fr.cnam.projetSiw.client.structure.pages.suggest;

import java.util.ArrayList;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

import fr.cnam.projetSiw.client.core.ClientFactory;
import fr.cnam.projetSiw.client.core.ContextKeeper;
import fr.cnam.projetSiw.client.core.GeolocationManager;
import fr.cnam.projetSiw.client.core.ZicActivity;
import fr.cnam.projetSiw.client.services.SparqlService;
import fr.cnam.projetSiw.client.services.SparqlServiceAsync;
import fr.cnam.projetSiw.shared.Track;

public class RecordTrackActivity extends ZicActivity implements RecordTrackView.Presenter
{

	private SparqlServiceAsync sparqlService = GWT.create(SparqlService.class);

	public RecordTrackActivity(ClientFactory clientFactory)
	{
		super(clientFactory);
	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus)
	{
		final RecordTrackView view = clientFactory.getRecordTrackView();
		view.setPresenter(this);
		panel.setWidget(view);
		
		getSongList(view);
		
		eventBus.addHandler(GenreChangedEvent.TYPE, new GenreChangeHandler() {
			
			@Override
			public void onCategoryChange(GenreChangedEvent event) {
				if(event.getGenre() != ""){
					ContextKeeper.getInstance().setGenre(event.getGenre());
					getSongList(view);
				}
			}
		});

	}

	private void getSongList(final RecordTrackView view) {
		GeolocationManager manager = GeolocationManager.getInstance();

		sparqlService.getSongNameRecordedInCityByGenre(manager.getCity().getName(), ContextKeeper.getInstance().getGenre(),  new AsyncCallback<ArrayList<Track>>()
		{

			@Override
			public void onFailure(Throwable caught)
			{
			}

			@Override
			public void onSuccess(ArrayList<Track> result)
			{
					view.setData(result);
			}
		});
	}
}
